package com.ybkj.daijia.api.weixin.handler.impl;

import com.alibaba.fastjson.JSONObject;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.WxSetting;
import com.ybkj.daijia.api.weixin.WxMsgType;
import com.ybkj.daijia.api.weixin.entity.WxBaseMsgEntity;
import com.ybkj.daijia.api.weixin.entity.WxBaseRespEntity;
import com.ybkj.daijia.api.weixin.entity.WxMsgTextEntity;
import com.ybkj.daijia.api.weixin.entity.WxRespTextEntity;
import com.ybkj.daijia.common.RandomString;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.server.event.model.ActivityCheckEvent;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.SmsTemplet;
import com.ybkj.daijia.server.model.SmsTemplet.SmsType;
import com.ybkj.daijia.server.model.WxBind;
import com.ybkj.daijia.server.reactor.ReactorVo;
import com.ybkj.daijia.server.sales.Activity.ActivityEvent;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.MemberAccountService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.SmsService;
import com.ybkj.daijia.server.service.WxBindService;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;

@Component
public class WxBindAccountHandler extends AbstractWxTextHandler {

    private static final Logger logger = LoggerFactory.getLogger(WxBindAccountHandler.class);

    @Autowired
    private WxBindService wxBindService;

    @Autowired
    private MemberAccountService memberAccountService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private TaskExecutor taskExecutor;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    @Autowired
    private SmsService smsService;

    @Override
    public boolean canHandle(WxBaseMsgEntity msg) {
        return super.canHandle(msg);
    }


    @Override
    public WxBaseRespEntity handleText(WxMsgTextEntity msg, Map<String, Object> context,
        WxBaseRespEntity resp) {

        WxSetting setting = settingUtils.getWx();

        //获取发送者号码

        String fromUser = msg.getFromUserName();
        String content = msg.getContent();

        content = StringUtils.trimToEmpty(content);
        Pattern pattern = Pattern.compile("^((\\+86)|(86))?((1)\\d{10})$");
        Matcher matcher = pattern.matcher(content);

        if (matcher.matches()) {

            final String phone = matcher.group(4);

            WxBind bind = wxBindService.findByWxuser(fromUser);

            String number = StringUtils.EMPTY;

            if (null == bind) {
                number = String.valueOf(RandomString.randomNum(4));
                bind = new WxBind();
                bind.setWxuser(fromUser);
                bind.setPhone(phone);
                bind.setCode(number);
                bind.setStatus(WxBind.WXBIND_STATUS_WAIT);
                wxBindService.insertRecrod(bind);
            } else if (bind.getStatus() == WxBind.WXBIND_STATUS_WAIT) {

                long diff = (System.currentTimeMillis() - bind.getUpdated().getTime()) / 1000 / 60;

                if (diff > 30) {
                    number = String.valueOf(RandomString.randomNum(4));
                } else {
                    number = bind.getCode();
                }
                bind.setCode(number);
                bind.setPhone(phone);

                wxBindService.updateByPrimaryKey(bind);
            } else {
                return resp;
            }

            final String numberStr = number;

            final Company mainCompany = companyService.getMain();
            if (StringUtils.isNotBlank(mainCompany.getSignName())) {
                taskExecutor.execute(new Runnable() {
                    public void run() {
                        int ret = -99;
                        try {
                            SmsTemplet templet = smsService
                                .findByAlias(mainCompany.getId(), SmsType.customDriver);
//							if(templet==null){
//								SmsTemplet smsTemplet=new SmsTemplet();
//								smsTemplet.setCompanyId(mainCompany.getId());
//								smsTemplet.setContent("{content}");
//								smsTemplet.setSmsType(SmsTemplet.SmsType.customMember);
//								smsService.insertSmsTemplate("给客户发自定义短信",SmsTemplet.SMSTEMPLATE_TYPE_CODE, smsTemplet);
//							}
                            if (templet != null && StringUtils.isNotBlank(templet.getContent())) {
                                //ret=smsService.sendSms(phone, "customMember", "{\"content\":\""+"您的验证码是："+numberStr+"\"}",mainCompany.getId(), 2, mainCompany.getSignName());
                                //短信发送（改）
                                JSONObject smsParam = new JSONObject();
                                smsParam.put("code", numberStr);
                                ret = smsService.sendSms(phone, templet.getTemplateId(),
                                    smsParam.toJSONString(), mainCompany.getId(), 2,
                                    mainCompany.getSignName());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        logger.debug("接收短信结果：" + ret);
                    }
                });
            }

            //绑定手机号逻辑
            WxRespTextEntity text = new WxRespTextEntity();
            text.setContent(setting.getWxAccountBindRequest());
            text.setCreatedDate(new Date());
            text.setCreateTime(text.getCreatedDate().getTime());
            text.setFromUserName(msg.getToUserName());
            text.setToUserName(msg.getFromUserName());
            text.setFuncFlag(0);
            text.setMsgType(WxMsgType.text.name());

            return text;

        }

        Pattern pattern2 = Pattern.compile("^\\d{4}$");
        Matcher matcher2 = pattern2.matcher(content);
        if (matcher2.matches()) {

            //查询是否有需要绑定的手机号
            WxBind bind = wxBindService.findByWxuser(fromUser);

            if (null != bind && bind.getStatus() == WxBind.WXBIND_STATUS_WAIT) {

                long diff = (System.currentTimeMillis() - bind.getUpdated().getTime()) / 1000 / 60;

                if (!content.equals(bind.getCode())) {

                    WxRespTextEntity text = new WxRespTextEntity();
                    text.setContent("很抱歉您输入的验证码错误，请从新输入。");
                    text.setCreatedDate(new Date());
                    text.setCreateTime(text.getCreatedDate().getTime());
                    text.setFromUserName(msg.getToUserName());
                    text.setToUserName(msg.getFromUserName());
                    text.setFuncFlag(0);
                    text.setMsgType(WxMsgType.text.name());

                    return text;

                } else if (diff > 30) {

                    WxRespTextEntity text = new WxRespTextEntity();
                    text.setContent("很抱歉您输入的验证码已经过期，请从新输入手机号码获取验证码。");
                    text.setCreatedDate(new Date());
                    text.setCreateTime(text.getCreatedDate().getTime());
                    text.setFromUserName(msg.getToUserName());
                    text.setToUserName(msg.getFromUserName());
                    text.setFuncFlag(0);
                    text.setMsgType(WxMsgType.text.name());

                    return text;

                } else {
                    //添加客户
                    String phone = bind.getPhone();
                    Passenger passenger = memberService.findOnePassengerByPhone(phone);
                    if (null == passenger) {

                        passenger = new Passenger();
                        passenger.setType(Passenger.TYPE_PASSENGER);
                        passenger.setChannel_name(Passenger.PASSENGER_CHANNEL_WEIXIN);
                        passenger.setAllowOverdraw(Boolean.FALSE);

                        Company company = companyService.getMain();
                        passenger.setCompanyId(company.getId());
                        passenger.setCompanyName(company.getAbbreviation());
                        Result<Passenger> result = memberService.createPersonal(passenger);

                        if (result.isSuccess()) {
                            //新注册活动
                            ReactorVo rVo = new ReactorVo();
                            rVo.setPassenger(result.getResult());
                            rVo.setActivityEvent(ActivityEvent.newRegister);
                            ActivityCheckEvent activityCheckEvent = new ActivityCheckEvent(rVo);
                            applicationEventMulticaster.multicastEvent(activityCheckEvent);
                        }

                    }

                    bind.setStatus(WxBind.WXBIND_STATUS_SUCCESS);
                    wxBindService.updateByPrimaryKey(bind);

                    String bindSuccess = setting.getWxAccountBindSuccess();

                    String message = "绑定成功,已绑定手机号码为：" + bind.getPhone() + "。";

                    if (!StringUtils.isBlank(bindSuccess)) {

                        message = bindSuccess.replaceAll("\\{phone\\}", bind.getPhone());
                    }

                    WxRespTextEntity text = new WxRespTextEntity();
                    text.setContent(message);
                    text.setCreatedDate(new Date());
                    text.setCreateTime(text.getCreatedDate().getTime());
                    text.setFromUserName(msg.getToUserName());
                    text.setToUserName(msg.getFromUserName());
                    text.setFuncFlag(0);
                    text.setMsgType(WxMsgType.text.name());

                    return text;
                }

            }


        }

        return resp;
    }

}
